<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_Module_Customsmartytags extends JFX_Module {

    public $keyname = 'customsmartytags';
    public $title = 'Custom Smarty Tags';
    public $version = '0.2.9';
    public $dependencies = array(
        array(
            'keyname' => 'content',
            'version' => '0.2.9'
        )
    );

    public function getBlockActions(){
        return array(
            array(
                'title' => 'Insert Block',
                'keyname' => 'insert'
            )
        );
        
    }










    public function copy($action, $oldBlockid, $newBlockid, $oldPageid, $newPageid, $oldWorkspaceid, $newWorkspaceid){
        return $this->copyToNewBlock($oldBlockid, $newBlockid, $oldWorkspaceid, $newWorkspaceid);
    }

    public function copyToNewBlock($oldid, $newid, $oldworkspaceid, $newworkspaceid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $dbParams = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}cst_blocks WHERE block_id = '{$oldid}'");
        $dbParams['block_id'] = $newid;
        unset($dbParams['id']);
        if($DB->countRows($CONFIG->dbprefix.'cst_blocks', "block_id = '{$safeBlockid}'")>0){
            $DB->update($CONFIG->dbprefix.'cst_blocks', $dbParams, "block_id = '{$safeBlockid}'");
        }else{
            $DB->insert($CONFIG->dbprefix.'cst_blocks', $dbParams);
        }
    }

    public function updateSettings($params){

        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $VIEW = JFX::registry('JFX_View');

        $id = $params['id'];






        if(Antz_IntelliForm::submitted('edit-tag')){
            $error = false;
            $code = post('code', '', 500000);
            $tagid = (int) post('tagid');
            $allowOverwrite = (int) post('allowOverwrite', 0);

            if($allowOverwrite == 1 && $DB->countRows($CONFIG->dbprefix.'cst_tags', "id = '{$tagid}' AND is_block = 1")>0){
                $tData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}cst_tags WHERE id = '{$tagid}'");
                $code = $tData['code'];
                $tagname = $tData['tagname'];
                $_POST['code'] = $code;
            }else if($allowOverwrite == 1){
                JFX::addError('Invalid tag name');
                $error = true;
            }

            if(!$error){
                $dbParams = array(
                    'code' => $code
                );
                if(isset($tagname)){
                    $dbParams['tagname'] = $tagname;
                }
                $DB->update($CONFIG->dbprefix.'cst_blocks', $dbParams, "block_id = '{$id}'");
                JFX::addSuccess($this->lang('updated_ok'));
            }

        }









        $bData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}cst_blocks WHERE block_id = '{$id}'");
       

        $tagOpts = array();
        $tags = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}cst_tags WHERE is_block = 1 ORDER BY tagname ASC");
        foreach($tags as $k=>$v){
            $tagOpts[$v['id']] = $v['tagname'];
        }

        

        $formFields = array(
            array(
                'type' => 'checkbox',
                'name' => 'allowOverwrite',
                'value' => '1',
                'checked' => false,
                'label' => $this->lang('form_allow_overwrite'),
                'id' => 'allowOverwrite'
            ),
            array(
                'type' => 'select',
                'options' => $tagOpts,
                'name' => 'tagid',
                'value' => post('tagid', $bData['tagname']),
                'label' => '&nbsp;',
                'id' => 'tagId',
                'disabled' => true
            ),
            array(
                'type' => 'code',
                'name' => 'code',
                'value' => post('code', $bData['code']),
                'label' => $this->lang('form_code'),
                'class' => 'php',
                'id' => 'cstcode'
            ),
            array(
                'type' => 'submit',
                'name' => 'submitBtn',
                'value' => $this->lang('form_save'),
                'label' => '&nbsp;'
            )
        );
        
        echo JFX::makeRapidForm($formFields, $this->lang('form_legend_edit'), 'edit-tag');


        $js = <<<JS
$(document).ready(function(){
    $('#allowOverwrite_0').change(function(){
        
        if(this.checked){
            $('#tagId').get(0).disabled = false;
            $('#cstcode_component').css('display', 'none');
        }else{
            $('#tagId').get(0).disabled = true;
            $('#cstcode_component').css('display', 'block');
        }
    });
});
JS;


        $VIEW->addJs($js);



    }




    public function __construct(){
        parent::__construct();
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $SMARTY = JFX::registry('Smarty');

        if($DB->countRows($CONFIG->dbprefix.'modules', "keyname = '{$this->keyname}'")==0) return;

        $tags = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}cst_tags");
        foreach($tags as $k=>$v){
            if(!function_exists("jfx_module_customsmartytags_tag_".$v['tagname'])) eval("function jfx_module_customsmartytags_tag_".$v['tagname']."(\$params, &\$smarty){
".$v['code']."
}");
            $SMARTY->register_function($v['tagname'], "jfx_module_customsmartytags_tag_".$v['tagname']);
        }
        $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}cst_blocks");
        foreach($blocks as $k=>$v){
            if(!function_exists('jfx_module_customsmartytags_block_'.$v['tagname'])) eval("function jfx_module_customsmartytags_block_".$v['tagname']."(\$params, \$content, &\$smarty, &\$repeat){
".$v['code']."
}");
            $SMARTY->register_block($v['tagname'], "jfx_module_customsmartytags_block_".$v['tagname']);
        }
    }


    public function getContent($params){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $LANG = JFX::registry('lang');
        $LINKER = JFX::registry('JFX_Link');
        $SMARTY = JFX::registry('Smarty');
        $VIEW = JFX::registry('JFX_View');
        $USER = JFX::registry('JFX_User');
        
        $blockid = $DB->escape($params['id']);


        $code = $DB->oneValue($CONFIG->dbprefix.'cst_blocks', 'code', "block_id = '{$blockid}'");
        if(trim($code) === '//REFERENCE'){
            $tagname = $DB->oneValue($CONFIG->dbprefix.'cst_blocks', 'tagname', "block_id = '{$blockid}'");
            $code = $DB->oneValue($CONFIG->dbprefix.'cst_tags', 'code', "tagname = '{$tagname}'");
        }
        ob_start();
        eval($code);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }


    public function prepare($details){
        
        return $this->getContent($details);
    }


    public function admin($url, $dirname){
        //$this->resetLanguages();
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);
        $THEME = JFX::registry('JFX_Theme');

        $THEME->addBreadcrumb($this->adminUrl, $this->getTitle());

        $this->addStylesheet('admin.css');

        $tabs = array(
            array(
                'keyname' => 'list',
                'title' => $this->lang('list_tags'),
                'url' => $url.'/list'
            )
        );

        // find our selected tab
        $urlParts = explode('?', THIS_PAGE_URL);
        $urlParts = explode('/', str_replace($CONFIG->baseUrl, '', $urlParts[0]));
        foreach($urlParts as $k=>$v){
            if($v == $this->keyname) break;
        }
        $selectedTab = (array_key_exists($k+1, $urlParts))
            ? $urlParts[$k+1]
            : ''
            ;

        if($selectedTab == ''){
            $selectedTab = 'list';
        }

        foreach($tabs as $k=>$tab){
            if($selectedTab == $tab['keyname']){
                $tabs[$k]['class_name'] = 'selected';
            }
        }

        //include('admin-actions/tabs.php');

        $selectedTab = str_replace('../', '/', $selectedTab);

        echo '<div id="cst-admin-tab-content"><div id="cst-admin-tab-content-inner">';
            if(file_exists($dirname.'/admin-actions/'.$selectedTab.'.php')) include('admin-actions/'.$selectedTab.'.php');
            else echo $selectedTab.'.php '.$this->lang('selected_tag_doesnt_exist');
        echo '</div></div>';

        
    }


    public function install(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/install.php');
    }


    public function uninstall(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/uninstall.php');
    }




}